<template>
  <div>
    <!-- - 原始相机 不兼容时的回退方案 -->
    <input
      ref="upload"
      type="file"
      accept="image/*"
      capture="camera"
      style="display: none"
    />
    <!-- 2 自定义相机 -->
    <div
      style="width: 100%; position: fixed; left: 0; bottom: 0; top: 0; right: 0"
      v-if="cameraShow"
    >
      <!-- 中间部分 -->
      <video
        ref="video"
        style="height: 100vh; width: 100vw; position: fixed; top: 0; left: 0"
      ></video>
      <div style="width: 100%; position: fixed; inset: 0">
        <!-- a.拍摄时展示取景框。把取景框图片换下就可以了 -->
        <!-- <img
          src="@/assets/main/finder.png"
          style="width: 100%; height: 100%; opacity: 0.6"
        /> -->
        <div class="finder">
          <div class="finder-box flex justify-between flex-col">
            <div class="top flex justify-between">
              <div class="info dashed"></div>
              <div class="dashed w-1/5"></div>
            </div>
            <div class="flex justify-between h-1/4">
              <div class="dashed w-1/3"></div>
              <div class="photo solid"></div>
            </div>
          </div>
        </div>
        <!-- b.拍摄完后展示抓拍图片 -->
        <!-- <img
          :src="imageUrl"
          alt=""
          v-if="status == 2"
          style="width: 100%; height: 100%"
        /> -->
      </div>

      <!-- 底下控制部分-->
      <!-- <div class="control">
        <div class="control_before">
          <div class="control_before_top">照片</div>
          <div class="control_before_bottom">
            <div class="smaller">取消</div>
            <i class="iconfont icon-xiangji bigger" @click="snapPhoto"></i>
          </div>
        </div>
        <div class="control_after" v-if="status==2">
        <div class="smaller" @click="status=1">重拍</div>
        <div class="smaller" @click="submitPhoto('custom')">使用照片</div>
      </div>
      </div> -->

      <!-- 抓拍 -->
      <canvas id="mycanvas"></canvas>
    </div>
  </div>
</template>

<script>
// import { fetchRefletAuth } from '@/api'

export default {
  name: 'FaceRecognition',
  props: {},
  data() {
    return {
      cameraShow: false
    }
  },
  created() {},
  mounted() {
    console.log(this.$route.query)
    this.$route.query.normal ? this.originCamera() : this.openCamera()
  },
  methods: {
    openCamera() {
      this.cameraShow = true
      let constraints = {
        video: {
          // facingMode: { exact: 'environment' },
          width: { ideal: 1280 },
          height: { ideal: 720 }
        }
      }
      // 老的浏览器可能根本没有实现 mediaDevices，所以我们可以先设置一个空的对象
      if (navigator.mediaDevices === undefined) {
        navigator.mediaDevices = {}
      }
      // 一些浏览器部分支持 mediaDevices。我们不能直接给对象设置 getUserMedia
      // 因为这样可能会覆盖已有的属性。这里我们只会在没有getUserMedia属性的时候添加它。
      if (navigator.mediaDevices.getUserMedia === undefined) {
        navigator.mediaDevices.getUserMedia = function (constraints) {
          // 首先，如果有getUserMedia的话，就获得它
          var getUserMedia =
            navigator.getUserMedia ||
            navigator.webkitGetUserMedia ||
            navigator.mozGetUserMedia
          // 一些浏览器根本没实现它 - 那么就返回一个error到promise的reject来保持一个统一的接口
          if (!getUserMedia) {
            return Promise.reject(
              new Error('getUserMedia is not implemented in this browser')
            )
          }
          // 否则，为老的navigator.getUserMedia方法包裹一个Promise
          return new Promise(function (resolve, reject) {
            getUserMedia.call(navigator, constraints, resolve, reject)
          })
        }
      }

      // 4. 获取视频流
      navigator.mediaDevices
        .getUserMedia(constraints)
        .then(stream => {
          // 进来这里表示能够兼容
          let video = this.$refs.video
          // 旧的浏览器可能没有srcObject
          if ('srcObject' in video) {
            video.srcObject = stream
          } else {
            // 防止在新的浏览器里使用它，应为它已经不再支持了
            video.src = window.URL.createObjectURL(stream)
          }
          video.onloadedmetadata = function (e) {
            video.play()
          }
        })
        .catch(err => {
          // 进来这里表示不能兼容
          console.log('nonono', err)
          // 调用原始摄像头
          // this.originCamera()
          this.$toast.fail('失败了')
        })
    },
    snapPhoto() {
      var canvas = document.querySelector('#mycanvas')
      var video = document.querySelector('video')
      canvas.width = video.videoWidth
      canvas.height = video.videoHeight
      canvas.getContext('2d').drawImage(video, 0, 0)

      // 保存为文件，用于后续的上传至服务器（尚未实践）——>后续提交
      this.imageFile = this.canvasToFile(canvas)

      // blob转url：用于展示
      new Promise((resolve, reject) => {
        canvas.toBlob(blob => {
          let url = URL.createObjectURL(blob)
          resolve(url)
        })
      }).then(value => {
        this.imageUrl = value
        // this.status = 2 //表示拍摄完成
      })
    },
    canvasToFile(canvas) {
      var dataurl = canvas.toDataURL('image/png')
      var arr = dataurl.split(','),
        mime = arr[0].match(/:(.*?);/)[1],
        bstr = window.atob(arr[1]),
        n = bstr.length,
        u8arr = new Uint8Array(n)
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n)
      }
      var file = new File([u8arr], 'phone.png', { type: mime })
      return file
    },
    originCamera() {
      //关闭自定义相机
      this.cameraShow = false
      new Promise((resolve, reject) => {
        this.$refs.upload.dispatchEvent(new MouseEvent('click'))
        this.$refs.upload.onchange = function (event) {
          if (!event) {
            reject('empty')
          }
          //当选中或者拍摄后确定图片后，保存图片文件——>后续提交
          let file = event.target.files[0]
          console.log(file)
          resolve(file)
        }
      }).then(value => {
        // this.submitPhoto('origin', value)
      })
    },
    handleChange() {
      const file = this.$refs.upload.files[0]
      const formData = new FormData()
      formData.append('image', file)
      console.log(file)

      // if (file.size > )

      //  this.$refs.upload.value = null // 上传成功清理
    },
    takePhoto() {
      //获得Canvas对象
      const canvas = this.$refs.canvas
      const ctx = canvas.getContext('2d')
      ctx.drawImage(this.video, 0, 0, 500, 500)
    },
    photoCompress(base64Url, imgAttr, callback) {
      var img = new Image()
      img.src = base64Url
      img.onload = function () {
        var that = this
        // 默认按比例压缩
        var w = that.width
        var h = that.height
        // 宽高比例
        var scale = w / h
        w = imgAttr.width || w
        h = imgAttr.height || w / scale
        // 默认图片质量为0.7
        var quality = 0.7
        // 生成canvas
        var canvas = document.createElement('canvas')
        var ctx = canvas.getContext('2d')
        // 创建属性节点
        var anw = document.createAttribute('width')
        anw.nodeValue = w
        canvas.setAttributeNode(anw)
        var anh = document.createAttribute('height')
        anh.nodeValue = h
        canvas.setAttributeNode(anh)
        ctx.drawImage(that, 0, 0, w, h)
        // 图像质量（0-1）
        if (imgAttr.quality && imgAttr.quality <= 1 && imgAttr.quality > 0) {
          quality = imgAttr.quality
        }
        // 重绘后的图⽚类型
        var imgType = imgAttr.type || 'image/jpeg'
        // quality值越小，所绘制出的图像越模糊
        var base64 = canvas.toDataURL(imgType, quality)
        // 回调函数返回base64的值
        callback(base64)
      }
    }
  }
}
</script>

<style lang="less" scoped>
.finder {
  width: 100%;
  height: 100%;
  opacity: 0.6;
  border: 40px solid rgba(0, 0, 0, 0.8);
  border-top-width: 100px;
  border-bottom-width: 180px;

  &-box {
    height: 100%;
    width: 100%;
    border: 2px solid white;
    border-radius: 5px;
    padding: 20px 30px;
    box-shadow: 0 0 0 0 transparent inset, 0 0 0 5px rgba(0, 0, 0, 0.8);
  }
}
.top {
  height: calc(75% - 10px);
}
.info {
  height: 100%;
  width: calc(80% - 10px);
}

.photo {
  height: 100%;
  width: calc(67% - 10px);
}
.dashed {
  border: 1px dashed white;
  border-radius: 5px;
}
.solid {
  border: 1px solid white;
  border-radius: 5px;
}
</style>
